﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace FierceWar
{
	public class TypingMessage
	{
		private GameResources _resources;

		// Position of the message.
		public Vector2 Position;
		public float OriginY = 200.0f;

		private string _message;
		public string Message
		{
			get
			{
				return _message;
			}
			set
			{
				_message = value;
				Vector2 fontText = Font.MeasureString(_message);
				Position = new Vector2(
					(_resources.GraphicsDevice.Viewport.Width - fontText.X) / 2,
					(_resources.GraphicsDevice.Viewport.Height - fontText.Y) / 2);
				Reset();
			}
		}

		// Part of the message has been drawn.
		private string _drawnMessage;
		// Index of the last character of the message has been drawn.
		private int _currentIndex;

		public SpriteFont Font;

		// Time to draw new letter.
		private float _timeToNextLetter;
		public float TimeToNextLetter
		{
			get
			{
				return _timeToNextLetter;
			}
			set
			{
				_timeToNextLetter = value;
				_stopwatchNextLetter = _timeToNextLetter;
			}
		}
		// Stopwatch for determining the time to draw next letter.
		private float _stopwatchNextLetter;

		// Typing effect is continous ?
		private bool _isTyping;

		public Color Color;

		public TypingMessage(GameResources resources, SpriteFont font,
			string message, Color color)
		{
			_resources = resources;
			Font = font;
			Message = message;
			Color = color;
		}

		public void Reset()
		{
			_drawnMessage = string.Empty;
			_currentIndex = 0;
			_isTyping = true;
		}

		public void Update(GameTime gameTime)
		{
			if (_isTyping)
			{
				if (_currentIndex == 0)
				{
					_drawnMessage += _message[_currentIndex].ToString();
					if (_currentIndex != _message.Length - 1)
					{
						_currentIndex++;
					}
					else
					{
						_isTyping = false;
					}
					_stopwatchNextLetter = _timeToNextLetter;
				}
				else
				{
					_stopwatchNextLetter -=
						(float)gameTime.ElapsedGameTime.TotalMilliseconds;
					if (_stopwatchNextLetter < 0.0f)
					{
						_drawnMessage += _message[_currentIndex].ToString();
						if (_currentIndex != _message.Length - 1)
						{
							_currentIndex++;
						}
						else
						{
							_isTyping = false;
						}
						_stopwatchNextLetter = _timeToNextLetter;
					}
				}
			}
		}

		public void Draw()
		{
			// Draw shadow.
			_resources.SpriteBatch.DrawString(Font, _drawnMessage,
				new Vector2(Position.X, Position.Y + OriginY) + Vector2.One,
				Color.Black);
			// Draw text.
			_resources.SpriteBatch.DrawString(Font, _drawnMessage,
				new Vector2(Position.X, Position.Y + OriginY), Color);
		}
	}
}
